package com.xcf.controller.business.finance;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xcf.controller.base.BaseController;
import com.xcf.controller.base.ExportDataHandler;
import com.xcf.entity.Page;
import com.xcf.entity.business.entities.Entity;
import com.xcf.service.business.entities.EntityManager;
import com.xcf.service.business.finance.PaymentService;
import com.xcf.service.system.appuser.AppuserManager;
import com.xcf.service.system.menu.MenuManager;
import com.xcf.service.system.user.UserManager;
import com.xcf.util.DateUtil;
import com.xcf.util.Jurisdiction;
import com.xcf.util.PageData;
import com.xcf.util.ResponseResult;
/***
 * 付款管理
 * @author WongBin
 */
@Controller
@RequestMapping(value="/payment")
public class PaymentController extends BaseController implements ExportDataHandler{
	
	String menuUrl = "payment/index"; //菜单地址(权限用)
    final String base = "/business/finance";

	@Resource(name="menuService")
	private MenuManager menuService;
	@Resource(name="entityService")
	private EntityManager entityService;
	@Resource(name="userService")
	private UserManager userService;
	@Resource(name="appuserService")
	private AppuserManager appuserService;
	@Autowired
	private PaymentService paymentService;
	/**
     * 列表
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/index")
	public ModelAndView list()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(pd.getString("ENTITY_ID") == null || "".equals(pd.getString("ENTITY_ID").trim())){
				pd.put("ENTITY_ID", "1");										//默认列出第一组角色(初始设计系统用户和会员组不能删除)
			}
			PageData fpd = new PageData();
			fpd.put("ENTITY_ID", "0");
			List<Entity> entityList = entityService.listAllEntitiesByPId(fpd);		//列出组(页面横向排列的一级组)
			List<Entity> entityList_z = entityService.listAllEntitiesByPId(pd);		//列出此组下架角色
			pd = entityService.findObjectById(pd);							//取得点击的角色组(横排的)
			mv.addObject("pd", pd);
			mv.addObject("entityList", entityList);
			mv.addObject("entityList_z", entityList_z);
			mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
            mv.setViewName(base.concat("/paymentManage/payment_index"));

        } catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 付款信息
	 * @param page
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value="/findPayment")
	@ResponseBody
	public ResponseResult findPayment(int page) throws Exception{
		PageHelper.startPage(page, 10);
		PageData pd = new PageData();
		pd = this.getPageData();
		List<Map> list = paymentService.findPayment(pd);
		return ResponseResult.success(new PageInfo(list));
	}
	/**
	 * 付款明细
	 * @param page
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value="/findPaymentDetail")
	@ResponseBody
	public ResponseResult findPaymentDetail(int page) throws Exception{
		PageHelper.startPage(page, 10);
		PageData pd = new PageData();
		pd = this.getPageData();
		List<Map> list = new ArrayList<Map>();
		if(pd.getString("is_income_loan").equals("1")){
			list = paymentService.findPaymentDetail(pd);
		}else if(pd.getString("is_income_loan").equals("0")){
			list = paymentService.findPaymentIncomeDetail(pd);
		}
		
		return ResponseResult.success(new PageInfo(list));
	}
	/**
	 * 更新信息
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/updatePaymentInfo")
	@ResponseBody
	public String updatePaymentInfo()throws Exception{
		PageData pd = new PageData();
		pd=this.getPageData();
		paymentService.editState(pd);
		paymentService.editDetailState(pd);
		return null;
	}
	/**
	 * 拆分/预收
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/paymentSplitAndAdvance")
	public ModelAndView paymentSplitAndAdvance()throws Exception{
		ModelAndView view = new ModelAndView();
		view.setViewName(base.concat("/paymentManage/payment_split_and_advance"));
		return view;
		
	}
	/**
	 * 新增拆分记录信息
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/savePaymentRecord")
	@ResponseBody
	public String savePaymentRecord()throws Exception{
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData pdq = new PageData();
		if(!pd.getString("payment_amount").isEmpty()){
			float payment_amount = Float.parseFloat(pd.getString("payment_amount"));
			pdq.put("payment_amount", payment_amount);
		}
		if(!pd.getString("total_amount").isEmpty()){
			float total_amount = Float.parseFloat(pd.getString("total_amount"));
			pdq.put("total_amount", total_amount);
		}
		if(!pd.getString("early_payment").isEmpty()){
			float early_payment = Float.parseFloat(pd.getString("early_payment"));
			pdq.put("early_payment", early_payment);
		}
		if(!pd.getString("remaining_balance").isEmpty()){
			float remaining_balance = Float.parseFloat(pd.getString("remaining_balance"));
			pdq.put("remaining_balance", remaining_balance);
		}
		if(!pd.getString("payment_cost_id").isEmpty()){
			int payment_cost_id = Integer.parseInt(pd.getString("payment_cost_id"));
			pdq.put("payment_cost_id", payment_cost_id);
		}
		
		paymentService.addPaymentRecord(pdq);
		return null;
	}
	@RequestMapping(value="/findInvoiceCodeByBillCode")
	@ResponseBody
	public ResponseResult findInvoiceCodeByBillCode(int page) throws Exception{
		PageHelper.startPage(page, 10);
		PageData pd = new PageData();
		pd = this.getPageData();
		List<Map> list = paymentService.findInvoiceCodeByBillCode(pd);
		return ResponseResult.success(new PageInfo(list));
	}
	@RequestMapping(value="/findBillCodeByInvoiceCode")
	@ResponseBody
	public ResponseResult findBillCodeByInvoiceCode(int page) throws Exception{
		PageHelper.startPage(page, 10);
		PageData pd = new PageData();
		pd = this.getPageData();
		List<Map> list = paymentService.findBillCodeByInvoiceCode(pd);
		return ResponseResult.success(new PageInfo(list));
	}
	@RequestMapping(value="/findAmountByCode")
	@ResponseBody
	public ResponseResult findAmountByCode(int page) throws Exception{
		PageHelper.startPage(page, 10);
		PageData pd = new PageData();
		pd = this.getPageData();
		List<Map> list = paymentService.finAmountByCode(pd);
		return ResponseResult.success(new PageInfo(list));
	}
	
	/**
	 *冲抵处理
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/savePaymentIntoRecord")
	@ResponseBody
	public String savePaymentIntoRecord()throws Exception{
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData pdq = new PageData();
		if(!pd.getString("payment_amount").isEmpty()){
			float payment_amount = Float.parseFloat(pd.getString("payment_amount"));
			pdq.put("payment_amount", payment_amount);
		}
		if(!pd.getString("total_amount").isEmpty()){
			float total_amount = Float.parseFloat(pd.getString("total_amount"));
			pdq.put("total_amount", total_amount);
		}
		if(!pd.getString("early_payment").isEmpty()){
			float early_payment = Float.parseFloat(pd.getString("early_payment"));
			pdq.put("early_payment", early_payment);
		}
		if(!pd.getString("remaining_balance").isEmpty()){
			float remaining_balance = Float.parseFloat(pd.getString("remaining_balance"));
			pdq.put("remaining_balance", remaining_balance);
		}
		if(!pd.getString("payment_cost_id").isEmpty()){
			int payment_cost_id = Integer.parseInt(pd.getString("payment_cost_id"));
			pdq.put("payment_cost_id", payment_cost_id);
		}
		
		paymentService.addPaymentRecord(pdq);
		PageData pdqw = new PageData();
		pdqw.put("is_offset", "1");
		pdqw.put("bill_code", pd.getString("bill_code"));
		pdqw.put("invoice_code", pd.getString("invoice_code"));
		pdqw.put("id", pd.getString("payment_cost_id"));
		//冲抵发票的剩余金额
		pdqw.put("amount", pd.getString("surplusAmount"));
		PageData remark = paymentService.findPaymentCostInfoByid(pd.getString("payment_cost_id"));
		String payment_remark = null;
		if(remark==null){
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			payment_remark = "业务编号："+pd.getString("bill_code")+",发票号："+pd.getString("invoice_code")+",抵冲了"+pd.getString("payment_amount")+",日期"+df.format(new Date());
		}else{
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			payment_remark = remark.getString("payment_remark")+";"+"业务编号："+pd.getString("bill_code")+",发票号："+pd.getString("invoice_code")+",抵冲了"+pd.getString("payment_amount")+",日期"+df.format(new Date());
		}
		pdqw.put("payment_remark", payment_remark);
		paymentService.updateStateById(pdqw);
		paymentService.updateStateByCode(pdqw);
		return null;
	}
	/**
	 * 付款制单
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/paymentMakeSingle")
	public ModelAndView paymentMakeSingle()throws Exception{
		ModelAndView view = new ModelAndView();
		view.setViewName(base.concat("/paymentManage/payment_single"));
		return view;
		
	}
	@Override
	public List getData(String type, Map param, Page page) {
		List<Map<String,Object>> map = new ArrayList<Map<String,Object>>(); 
		List<Map> list = new ArrayList<Map>();
		try {
			list = paymentService.findPaymentDeatilInfo(param.get("payment_app_code").toString());
			Map mp = new HashMap<String,Object>();
			String USERNAME = Jurisdiction.getUsername();//当前登录的用户名        
			mp.put("list", list);
			mp.put("zhidan", "4848784");
			mp.put("settlement_dept",URLDecoder.decode(param.get("settlement_dept").toString(),"UTF-8"));
			mp.put("USERNAME", USERNAME);
			map.add(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	@Override
	public String getService() {
		// TODO Auto-generated method stub
		return  getClass().getSimpleName();
	}
	@Override
	public Map<String, String> setNames() {
		Map m = new HashMap(3);
		//保险申报单
		m.put("PaymentInfo","PaymentInfo.xls");
		m.put("PaymentInfoName","付款("+ DateUtil.getSdfTimes()+").xls");
		m.put("PaymentInfoModule",getService());
		return m;
	}
}
